const sendToWormhole = require("stream-wormhole");
var COS = require("cos-nodejs-sdk-v5");
const path = require("path");

const Controller = require("egg").Controller;
class TencentController extends Controller {
  async upload() {
    const {
      SecretId,
      SecretKey,
      Bucket,
      Region,
      Prefix,
    } = this.app.config.tencent;
    const cos = new COS({ SecretId, SecretKey });
    const { ctx } = this;
    const stream = await ctx.getFileStream();
    /**
     * @param {stream.filename} 文件名
     * @method path.extname(string)  获取后缀(.png)
     * @method string.toLocaleLowerCase() 字符串中的字母全部转为小写
     *
     * @description 最后的结果就是 现在的时间+上传文件的后缀
     */
    const filename =
      "test/" + Date.now() + path.extname(stream.filename).toLocaleLowerCase();
    var res = {};
    await new Promise((resolve, reject) => {
      cos.putObject(
        {
          Bucket,
          Region,
          Key: filename /* 必须 */,
          Body: stream, // 上传文件对象
        },
        (err, data) => {
          return err ? reject(err) : resolve(data);
        }
      );
    })
      .then((r) => {
        res.status = 1;
        res["url"] = Prefix + r.Location.split("/").slice(1).join("/");
      })
      .catch(() => {
        res.status = 0;
      });
    ctx.body = JSON.stringify(res);
  }
}

module.exports = TencentController;
